<template>
  <div>
    <el-container>
      <el-header style="margin-top: 10px;height: auto;">
        <el-row>
          <el-input
            v-model="kwInput"
            placeholder="输入关键字搜索 SOP 目标、学习资料、关键结果等"
            class="input-with-select"
            clearable
            @keyup.native.enter="handleSearch"
          >
            <el-button slot="append" icon="el-icon-search" @click="handleSearch">搜索</el-button>
          </el-input>
          <el-button
            type="primary"
            class="el-icon-plus add-btn"
            :disabled="listLoading"
            @click="handleAction('create', '添加SOP配置')"
          >添加SOP配置
          </el-button>
        </el-row>
      </el-header>
      <el-main>
        <el-table
          v-loading="listLoading"
          :data="data"
          border
          fit
          highlight-current-row
          style="width: 100%"
        >
          <el-table-column align="center" label="订单状态" width="180">
            <template slot-scope="scope">
              <el-tag
                effect="dark"
                :color="scope.row.crmorderstate_color"
              >
                {{ scope.row.crmorderstate_name }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column align="left" label="目标" prop="target" min-width="200">
            <template slot-scope="scope">
              <div class="text-overflow" :title="scope.row.target">
                {{ scope.row.target || '未设置' }}
              </div>
            </template>
          </el-table-column>
          <el-table-column align="left" label="学习资料" prop="learning_materials" min-width="200">
            <template slot-scope="scope">
              <div class="text-overflow" :title="scope.row.learning_materials">
                {{ scope.row.learning_materials || '未设置' }}
              </div>
            </template>
          </el-table-column>
          <el-table-column align="left" label="关键结果" prop="key_results" min-width="200">
            <template slot-scope="scope">
              <div class="text-overflow" :title="scope.row.key_results">
                {{ scope.row.key_results || '未设置' }}
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="预计耗时" prop="estimated_duration" width="100">
            <template slot-scope="scope">
              {{ scope.row.estimated_duration || 0 }}小时
            </template>
          </el-table-column>
          <el-table-column align="center" label="状态" width="80">
            <template slot-scope="scope">
              <el-tag
                :type="scope.row.is_active ? 'success' : 'danger'"
                size="mini"
              >
                {{ scope.row.is_active ? '启用' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column align="center" label="创建人" prop="creator_name" width="100" />
          <el-table-column align="center" label="创建时间" prop="create_at" width="150" />
          <el-table-column align="center" label="操作" width="200">
            <template slot-scope="scope">
              <el-button size="mini" type="primary" @click="handleAction('edit', scope.row)">
                编辑
              </el-button>
              <el-button size="mini" type="info" @click="handleAction('view', scope.row)">
                详情
              </el-button>
              <el-button size="mini" type="danger" @click="handleAction('delete', scope.row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          v-if="data.length"
          background
          class="mt-pagination"
          :current-page="page"
          :page-sizes="[10,20,50,100]"
          :page-size="pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
        <el-alert
          title="提示"
          type="info"
          description="SOP任务目标功能可以帮助团队明确每个订单状态下的工作目标、学习资料和关键结果，提高工作效率和规范性。"
          :closable="false"
        />
      </el-main>
    </el-container>

    <!-- 创建/编辑对话框 -->
    <el-dialog
      append-to-body
      :title="title"
      :width="dialogWidth"
      :visible.sync="innerDialogVisible"
      :close-on-click-modal="false"
      @closed="resetTemp"
    >
      <el-form
        v-if="action !== 'delete' && action !== 'view'"
        ref="dataForm"
        :model="temp"
        :rules="rules"
        label-position="top"
        label-width="120px"
      >
        <el-form-item label="关联订单状态" prop="crmorderstate_id">
          <el-select
            v-model="temp.crmorderstate_id"
            placeholder="选择订单状态"
            filterable
            :disabled="action === 'edit'"
            style="width: 100%"
            @focus="onSelectFocus"
            @visible-change="onSelectVisibleChange"
          >
            <el-option
              v-for="state in availableStates"
              :key="state.id"
              :label="state.name"
              :value="state.id"
            >
              <span :style="{color: state.color || '#409EFF'}">{{ state.name || '未知状态' }}</span>
            </el-option>
          </el-select>
          <div v-if="availableStates.length === 0" style="color: #ccc; font-size: 12px; margin-top: 5px;">
            {{ listLoading ? '正在加载状态选项...' : '暂无可用状态' }}
          </div>
          <div v-else style="color: #999; font-size: 12px; margin-top: 5px;">
            共 {{ availableStates.length }} 个可选状态
          </div>

          <!-- 调试信息面板 -->
          <el-collapse style="margin-top: 10px;">
            <el-collapse-item title="🔍 调试信息" name="debug">
              <div style="font-size: 12px; color: #666;">
                <p><strong>缓存状态数量:</strong> {{ allOrderStates.length }}</p>
                <p><strong>可用状态数量:</strong> {{ availableStates.length }}</p>
                <p><strong>当前操作模式:</strong> {{ action }}</p>
                <p><strong>选中状态ID:</strong> {{ temp.crmorderstate_id || '未选中' }}</p>
                <div v-if="availableStates.length > 0">
                  <p><strong>可用状态列表:</strong></p>
                  <ul style="margin: 0; padding-left: 20px;">
                    <li v-for="state in availableStates.slice(0, 5)" :key="state.id">
                      ID: {{ state.id }}, 名称: {{ state.name }}, 颜色: <span :style="{color: state.color}">{{ state.color }}</span>
                    </li>
                    <li v-if="availableStates.length > 5">... 还有 {{ availableStates.length - 5 }} 个</li>
                  </ul>
                </div>
              </div>
            </el-collapse-item>
          </el-collapse>
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="预计耗时(小时)" prop="estimated_duration">
              <el-input-number
                v-model="temp.estimated_duration"
                :min="0"
                :max="999"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-switch
                v-model="temp.is_active"
                active-text="启用"
                inactive-text="禁用"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="目标" prop="target">
          <el-input
            v-model="temp.target"
            type="textarea"
            :rows="3"
            placeholder="请描述该状态下需要达成的具体目标"
          />
        </el-form-item>

        <el-form-item label="学习资料" prop="learning_materials">
          <el-input
            v-model="temp.learning_materials"
            type="textarea"
            :rows="3"
            placeholder="请列出完成该状态所需的学习资料和参考文档"
          />
        </el-form-item>

        <el-form-item label="关键结果" prop="key_results">
          <el-input
            v-model="temp.key_results"
            type="textarea"
            :rows="3"
            placeholder="请描述该状态的关键成果和衡量标准"
          />
        </el-form-item>

        <el-form-item label="完成标准" prop="completion_criteria">
          <el-input
            v-model="temp.completion_criteria"
            type="textarea"
            :rows="2"
            placeholder="请描述状态完成的具体标准(可选)"
          />
        </el-form-item>
      </el-form>

      <!-- 查看详情 -->
      <div v-if="action === 'view'">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="订单状态">
            <el-tag :color="temp.crmorderstate_color">{{ temp.crmorderstate_name }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="预计耗时">{{ temp.estimated_duration || 0 }}小时</el-descriptions-item>
          <el-descriptions-item label="状态" :span="2">
            <el-tag :type="temp.is_active ? 'success' : 'danger'">
              {{ temp.is_active ? '启用' : '禁用' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="目标" :span="2">
            <div class="sop-content">{{ temp.target || '未设置' }}</div>
          </el-descriptions-item>
          <el-descriptions-item label="学习资料" :span="2">
            <div class="sop-content">{{ temp.learning_materials || '未设置' }}</div>
          </el-descriptions-item>
          <el-descriptions-item label="关键结果" :span="2">
            <div class="sop-content">{{ temp.key_results || '未设置' }}</div>
          </el-descriptions-item>
          <el-descriptions-item label="完成标准" :span="2">
            <div class="sop-content">{{ temp.completion_criteria || '未设置' }}</div>
          </el-descriptions-item>
          <el-descriptions-item label="创建人">{{ temp.creator_name || '未知' }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ temp.create_at }}</el-descriptions-item>
        </el-descriptions>
      </div>

      <!-- 删除确认 -->
      <div v-if="action === 'delete'" class="delete-confirm">
        <i class="el-icon-warning" style="color: #E6A23C; font-size: 24px;" />
        <span>确认要删除状态 <strong>{{ temp.crmorderstate_name }}</strong> 的SOP配置吗？</span>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="innerDialogVisible = false">取消</el-button>
        <el-button
          v-if="action !== 'view'"
          type="primary"
          :loading="confirmLoading"
          @click="confirmAction"
        >
          {{ action === 'delete' ? '确认删除' : '确认' }}
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { Get, Post, Put, Delete, GetOrderStateOptions } from '@/api/crm/crmorderstatesop'
import qs from 'qs'

export default {
  name: 'CRMOrderStateSOP',
  data() {
    return {
      kwInput: '',
      listLoading: false,
      data: [],
      total: 0,
      page: 1,
      pagesize: 20,

      innerDialogVisible: false,
      title: '',
      action: '',
      dialogWidth: '800px',
      confirmLoading: false,

      availableStates: [], // 可用的订单状态选项
      allOrderStates: [], // 缓存所有订单状态，避免重复获取

      temp: {
        crmorderstate_id: '',
        target: '',
        learning_materials: '',
        key_results: '',
        completion_criteria: '',
        estimated_duration: 0,
        is_active: true
      },

      rules: {
        crmorderstate_id: [
          { required: true, message: '请选择订单状态', trigger: 'change' }
        ],
        target: [
          { required: true, message: '请填写目标', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.fetchList()
  },

  mounted() {
    console.log('CRMOrderStateSOP组件已挂载')
    // 预加载订单状态选项，避免用户点击时等待
    this.preloadOrderStates()
  },
  methods: {
    async preloadOrderStates() {
      try {
        console.log('预加载订单状态选项...')
        const response = await GetOrderStateOptions()
        if (response && response.success) {
          this.allOrderStates = response.data || []
          console.log('预加载成功，缓存状态数量:', this.allOrderStates.length)
        }
      } catch (error) {
        console.log('预加载订单状态失败，将在需要时重新获取:', error.message)
      }
    },

    async fetchList() {
      this.listLoading = true
      try {
        const params = qs.stringify({
          page: this.page,
          pagesize: this.pagesize,
          kw: this.kwInput.trim()
        })

        const response = await Get(null, params)
        if (response && response.success) {
          this.data = response.data.data
          this.total = response.data.total
        } else {
          this.$message.error(response?.msg || '获取数据失败')
        }
      } catch (error) {
        console.error('获取SOP列表失败:', error)
        this.$message.error('获取数据失败')
      }
      this.listLoading = false
    },

    async fetchAvailableStates() {
      console.log('🔄 开始获取可用状态...')

      // 如果已有缓存，直接使用
      if (this.allOrderStates.length > 0) {
        console.log('💾 使用缓存的订单状态数据, 缓存数量:', this.allOrderStates.length)
        this.processAvailableStates()
        return
      }

      try {
        console.log('📡 发起API请求获取订单状态选项...')
        const response = await GetOrderStateOptions()
        console.log('📡 API响应原始数据:', response)
        console.log('📡 响应类型:', typeof response)
        console.log('📡 响应属性:', Object.keys(response || {}))

        // response 是被拦截器处理后的数据，直接就是返回的数据对象
        if (response && response.success) {
          // 缓存所有订单状态数据
          this.allOrderStates = response.data || []
          console.log(`✅ 获取订单状态成功，数量: ${this.allOrderStates.length}`)
          console.log('📊 前3个状态示例:', this.allOrderStates.slice(0, 3))

          // 处理可用状态
          this.processAvailableStates()
        } else {
          console.error('❌ API返回错误:', response?.msg || '响应格式错误')
          this.$message.error(response?.msg || '获取状态选项失败')
        }
      } catch (error) {
        console.error('❌ 获取状态选项失败:', error)
        this.$message.error('获取状态选项失败: ' + (error.response?.data?.msg || error.message))
      }
    },

    processAvailableStates() {
      // 从缓存中获取可用状态
      this.availableStates = [...this.allOrderStates]

      console.log('🔍 处理可用状态:')
      console.log('  - 原始缓存数据长度:', this.allOrderStates.length)
      console.log('  - 复制后数据长度:', this.availableStates.length)
      console.log('  - 前3个状态详情:', this.availableStates.slice(0, 3))

      // 如果是编辑模式，需要把当前选中的状态也加入到可选项中
      if (this.action === 'edit' && this.temp.crmorderstate_id) {
        const currentState = {
          id: this.temp.crmorderstate_id,
          name: this.temp.crmorderstate_name,
          color: this.temp.crmorderstate_color
        }
        if (!this.availableStates.find(s => s.id === currentState.id)) {
          this.availableStates.unshift(currentState)
          console.log('  - 已添加编辑状态:', currentState)
        }
      }

      console.log(`✅ 处理完成，可用状态数量: ${this.availableStates.length}`)

      // 强制触发Vue响应式更新
      this.$nextTick(() => {
        this.$forceUpdate()
      })
    },

    onSelectFocus() {
      console.log('🎯 选择器获得焦点, 当前可用状态数量:', this.availableStates.length)
    },

    onSelectVisibleChange(visible) {
      console.log('📋 选择器下拉框状态变化:', visible ? '打开' : '关闭')
      if (visible) {
        console.log('📝 当前可选项详情:', this.availableStates.map(s => ({ id: s.id, name: s.name })))
      }
    },

    handleSearch() {
      this.page = 1
      this.fetchList()
    },

    handleSizeChange(size) {
      this.pagesize = size
      this.fetchList()
    },

    handlePageChange(page) {
      this.page = page
      this.fetchList()
    },

    async handleAction(action, row) {
      console.log('🚀 处理操作:', action, row ? `行数据: ${row.id}` : '')
      this.action = action

      switch (action) {
        case 'create':
          console.log('📝 创建模式 - 开始处理')
          this.title = '添加SOP配置'
          this.dialogWidth = '800px'
          this.resetTemp()
          console.log('📝 创建模式 - temp已重置, 开始获取状态')
          await this.fetchAvailableStates()
          console.log('📝 创建模式 - 状态获取完成, availableStates长度:', this.availableStates.length)
          this.innerDialogVisible = true
          console.log('📝 创建模式 - 对话框已显示')
          break

        case 'edit':
          this.title = `编辑SOP配置 - ${row.crmorderstate_name}`
          this.dialogWidth = '800px'
          this.temp = Object.assign({}, row)
          await this.fetchAvailableStates()
          this.innerDialogVisible = true
          break

        case 'view':
          this.title = `SOP详情 - ${row.crmorderstate_name}`
          this.dialogWidth = '900px'
          this.temp = Object.assign({}, row)
          this.innerDialogVisible = true
          break

        case 'delete':
          this.title = '删除确认'
          this.dialogWidth = '500px'
          this.temp = Object.assign({}, row)
          this.innerDialogVisible = true
          break
      }
    },

    async confirmAction() {
      if (this.action === 'create' || this.action === 'edit') {
        this.$refs.dataForm.validate(async(valid) => {
          if (valid) {
            await this.submitForm()
          }
        })
      } else if (this.action === 'delete') {
        await this.deleteItem()
      }
    },

    async submitForm() {
      this.confirmLoading = true
      try {
        const data = Object.assign({}, this.temp)
        let response

        if (this.action === 'create') {
          response = await Post(data)
        } else {
          response = await Put(this.temp.id, data)
        }

        if (response && response.success) {
          this.$message.success(this.action === 'create' ? '创建成功' : '更新成功')
          this.innerDialogVisible = false
          // 如果是创建操作，需要清空缓存，因为可用状态列表发生了变化
          if (this.action === 'create') {
            this.allOrderStates = []
          }
          this.fetchList()
        } else {
          this.$message.error(response?.msg || '操作失败')
        }
      } catch (error) {
        console.error('提交失败:', error)
        this.$message.error('操作失败')
      }
      this.confirmLoading = false
    },

    async deleteItem() {
      this.confirmLoading = true
      try {
        const response = await Delete(this.temp.id)
        if (response && response.success) {
          this.$message.success('删除成功')
          this.innerDialogVisible = false
          // 删除操作后，需要清空缓存，因为可用状态列表发生了变化
          this.allOrderStates = []
          this.fetchList()
        } else {
          this.$message.error(response?.msg || '删除失败')
        }
      } catch (error) {
        console.error('删除失败:', error)
        this.$message.error('删除失败')
      }
      this.confirmLoading = false
    },

    resetTemp() {
      this.temp = {
        crmorderstate_id: '',
        target: '',
        learning_materials: '',
        key_results: '',
        completion_criteria: '',
        estimated_duration: 0,
        is_active: true
      }
      this.availableStates = []
      if (this.$refs.dataForm) {
        this.$refs.dataForm.clearValidate()
      }
    },

    notify(message, type = 'success', duration = 2000) {
      this.$notify({
        title: type === 'success' ? '成功' : '错误',
        message: message,
        type: type,
        duration: duration
      })
    }
  }
}
</script>

<style scoped>
.add-btn {
  margin-left: 10px;
}

.text-overflow {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 180px;
}

.sop-content {
  white-space: pre-wrap;
  word-break: break-all;
  line-height: 1.5;
}

.delete-confirm {
  text-align: center;
  padding: 20px;
}

.delete-confirm i {
  display: block;
  margin-bottom: 10px;
}

.mt-pagination {
  margin-top: 20px;
  text-align: right;
}

.el-descriptions {
  margin-top: 20px;
}

.dialog-footer {
  text-align: right;
}
</style>
